﻿using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using ARS.Control.Custom.Entity.Widget;

namespace ARS.Control.Custom.Entity.Fields
{
    public class SelectDbField:HiddenInputField
    {
        public string SqlCode { get; set; }

        /// <summary>
        /// 数据是不是来自于实体
        /// </summary>
        public bool IsFromEntity = true;

        public SelectDbField()
        {

        }

        public override void InitInputValue(EntityBaseControl entityBaseControl)
        {
            //SELECT 1 FROM cardrollbourse WHERE CodeFirst='0' and CodeTwo LIKE '%|01|%'
            if (IsFromEntity&&!string.IsNullOrEmpty(this.SqlCode))
            {
                Regex regex = new Regex(@"{{FieldName-(.*?)}}");
                MatchCollection matchs = regex.Matches(this.SqlCode);
                foreach (Match match in matchs)
                {
                    Field field = entityBaseControl.EntityTableInfo.FieldList.SingleOrDefault(
                        fied => fied.Db_Field_Name == match.Groups[1].Value);
                    if (field != null)
                    {
                        this.SqlCode = regex.Replace(this.SqlCode, field.Value.ToString(), 1);
                    }
                }                
                DbDataReader dbDataReader = ARS.DataBase.Provider.DbProvider.GetInstance().ExecuteReader(this.SqlCode);
                if (dbDataReader.Read())
                {
                    this.Value = dbDataReader[0];
                }
                dbDataReader.Close();
            }

        }

        public void InitInputValue(string sql)
        {
            if (!string.IsNullOrEmpty(sql))
            {
                DbDataReader dbDataReader = ARS.DataBase.Provider.DbProvider.GetInstance().ExecuteReader(sql);
                if (dbDataReader.Read())
                {
                    this.Value = dbDataReader[0];
                }
                dbDataReader.Close();
            }
        }
    }
}
